package cc.lotuscard;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

import com.dense.kuiniu.bookborrow.view.dialog.PutCardDialog;

import java.util.HashMap;

/**
 * @author Administrator
 * @date 2021/2/25
 */
public class LotusCardUtils {
    private final int mPid = 20763;
    private final int mVid = 1306;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private long mDeviceHandler = -1;
    private LotusCardDriver mLotusCardDriver;

    private Handler mHandler;
    private HandlerThread mHandlerThread;
    private LotusCardParam mLotusCardParam = new LotusCardParam();
    private PutCardDialog.OnCardReadListener mReadListener;

    private static final class Holder {
        private static final LotusCardUtils INSTANCE = new LotusCardUtils();
    }

    public static LotusCardUtils getInstance() {
        return Holder.INSTANCE;
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            int nRequestType = LotusCardDriver.RT_NOT_HALT;
            boolean result = mLotusCardDriver.GetCardNo(mDeviceHandler, nRequestType,
                    mLotusCardParam);
            if (result) {
                Log.e("result", bytes2long(mLotusCardParam.arrCardNo) + "");
                mLotusCardDriver.Beep(mDeviceHandler, 10);
                if (mReadListener != null) {
                    mReadListener.onComplete(String.valueOf(bytes2long(mLotusCardParam.arrCardNo)));
                }
            } else {
                mHandler.postDelayed(mRunnable, 1000);
                Log.e("result", "没有读到");
            }
        }
    };

    private LotusCardUtils() {
        mHandlerThread = new HandlerThread("handler-thread");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
    }


    public boolean findDevice(Context context) {
        boolean find = false;
        UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        if (usbManager != null) {
            UsbDevice targetDevice = null;
            HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
            if (!deviceList.isEmpty()) {
                for (UsbDevice device : deviceList.values()) {
                    if ((mVid == device.getVendorId())
                            && (mPid == device.getProductId())) {
                        targetDevice = device;
                        break;
                    }
                }
            }
            if (targetDevice != null) {
                UsbInterface usbInterface = targetDevice.getInterface(0);
                if (!usbManager.hasPermission(targetDevice)) {
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(
                            ACTION_USB_PERMISSION), 0);
                    usbManager.requestPermission(targetDevice, pendingIntent);
                }
                UsbDeviceConnection conn;
                if (usbManager.hasPermission(targetDevice)) {
                    conn = usbManager.openDevice(targetDevice);
                    if (conn != null) {
                        if (conn.claimInterface(usbInterface, true)) {
                            LotusCardDriver.m_UsbDeviceConnection = conn;
                        } else {
                            conn.close();
                        }
                        if (LotusCardDriver.m_UsbDeviceConnection != null) {
                            if (usbInterface.getEndpoint(1) != null) {
                                LotusCardDriver.m_OutEndpoint = usbInterface.getEndpoint(1);
                            }
                            if (usbInterface.getEndpoint(0) != null) {
                                LotusCardDriver.m_InEndpoint = usbInterface.getEndpoint(0);
                            }
                            find = true;
                            mLotusCardDriver = new LotusCardDriver();
                        }
                    }
                }
            }
        }
        return find;
    }

    public void startRead(PutCardDialog.OnCardReadListener listener) {
        mReadListener = listener;
        if (mLotusCardDriver == null) {
            return;
        }
        if (mDeviceHandler == -1) {
            mDeviceHandler = mLotusCardDriver.OpenDevice("", 0, 0, 0, 0, true);
        }
        if (mDeviceHandler != -1 && mHandler != null) {

            mHandler.post(mRunnable);
        }
    }

    public void stopRead() {
        mReadListener = null;
        mHandler.removeCallbacks(mRunnable);
    }

    public long bytes2long(byte[] byteNum) {
        long num = 0;
        for (int ix = 3; ix >= 0; --ix) {
            num <<= 8;
            if (byteNum[ix] < 0) {
                num |= (256 + (byteNum[ix]) & 0xff);
            } else {
                num |= (byteNum[ix] & 0xff);
            }
        }
        return num;
    }
} 